﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace GDCal.dao
{
    public class AbstractDao
    {
        public static String getConnectionString()
        {
            StringBuilder connection = new StringBuilder();
            connection.Append("Password=");
            connection.Append(GDCalConstants.GDCalConfig[GDCalConstants.dbPassword]);
            connection.Append(";User ID=");
            connection.Append(GDCalConstants.GDCalConfig[GDCalConstants.dbUsername]);
            connection.Append(";Initial Catalog=");
            connection.Append(GDCalConstants.GDCalConfig[GDCalConstants.dbName]);
            connection.Append(";Data Source=");
            connection.Append(GDCalConstants.GDCalConfig[GDCalConstants.dbServer]);

            return connection.ToString();
        }

        public static SqlConnection getConnection()
        {
            String SQL_CON = AbstractDao.getConnectionString();
            SqlConnection oConn = new SqlConnection(SQL_CON);
            if (oConn.State == ConnectionState.Closed)
            {
                try
                {
                    oConn.Open();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return oConn;
        }

        public static String connectToServer() {
            String ret = "OK";

            try
            {
                SqlConnection oConn = AbstractDao.getConnection();
                String testSQL = "SELECT 1";
                SqlCommand oComd = new SqlCommand(testSQL, oConn);
                oComd.CommandType = CommandType.Text;

                oComd.ExecuteReader();
            }
            catch (Exception ex) 
            {
                if (ex.InnerException != null)
                    ret = ex.InnerException.Message;
                else
                    ret = ex.Message;
            }

            return ret;
        }
    }
}
